#!/usr/bin/env python
# -*- coding:utf-8 -*-

import flask
from flask_restful import Resource, reqparse

from controller.studentController import StudentController
from service.studentService import StudentService
from flask import jsonify
from flask_restful import Resource, reqparse
from werkzeug.exceptions import BadRequest
from utils import commons
from utils.JwtMiddleware import TokenRequire
from utils.myLogging import logger
from utils.responseParser import ResponseParser
from utils.response_code import error_map_EN, RET
from utils.rsa_encryption_decryption import RSAEncryptionDecryption


class AdminUpdateResource(Resource):

    @classmethod
    @TokenRequire
    def update(cls, student_id):
        if not student_id:
            return jsonify(code=RET.NODATA, message='primary key missed', error='primary key missed')

        parser = reqparse.RequestParser()
        parser.add_argument('is_delete', location='form', required=False, help='is_delete参数类型不正确或缺失')
        parser.add_argument('student_name', location='form', required=True, help='student_name参数类型不正确或缺失')
        parser.add_argument('lesson_id', location='form', required=True, help='lesson_id参数类型不正确或缺失')

        kwargs = parser.parse_args()
        kwargs = commons.put_remove_none(**kwargs)
        kwargs['student_id'] = student_id

        res = StudentController.update(**kwargs)

        return jsonify(code=res['code'], message=res['message'], data=res['data'])

# 注册学生账号
class StuAddResource(Resource):
    @classmethod
    def post(cls):
        parser = reqparse.RequestParser()
        # parser.add_argument('UserID', location='args', required=False, help='UserID参数类型不正确或缺失')
        parser.add_argument('student_id', location='form', required=False, help='student_id参数类型不正确或缺失')
        parser.add_argument('password', location='form', required=False, help='password参数类型不正确或缺失')
        parser.add_argument('student_name', location='form', required=False, help='student_name参数类型不正确或缺失')
        parser.add_argument('phone', location='form', required=False, help='phone参数类型不正确或缺失')
        parser.add_argument('lesson_id', location='form', required=False, help='lesson_id参数类型不正确或缺失')
        try:
            kwargs = parser.parse_args()
            res = StudentService.get(student_id=kwargs.get("student_id"))
            if res.get("code") != RET.OK:
                logger.error(error_map_EN[res.get("code")])
                return jsonify({
                    "code": res.get("code"),
                    "error": res.get("data").get("error"),
                    "message": res.get("message"),
                })
            if res.get("totalCount") != 0:
                logger.error(error_map_EN[RET.DATAEXIST])
                return jsonify({
                    "code": RET.DATAEXIST,
                    "error": error_map_EN[RET.DATAEXIST],
                    "message": "用户账号信息已注册",
                })
            kwargs = commons.put_remove_none(**kwargs)
            res = StudentService.add(**kwargs)
            if res.get("code") != RET.OK:
                logger.error(res.get("data").get("error"))
                return jsonify({
                    "code": res.get("code"),
                    "error": res.get("data").get("error"),
                    "message": "用户注册失败",
                })
            logger.info(f"user {res.get('data').get('student_id')} register success")
            return jsonify({
                "code": RET.OK,
                "message": "用户注册成功",
            })
        except BadRequest as e:
            logger.error(str(e))
            return jsonify(ResponseParser.parse_param_error(error=str(e)))

        except Exception as e:
            logger.warning(str(e))
            return jsonify(ResponseParser.parse_unknown_error(error=str(e)))


# 修改学生账号信息
class StuUpdateResource(Resource):
    @classmethod
    @TokenRequire
    def put(cls):
        parser = reqparse.RequestParser()
        parser.add_argument('student_name', location='form', required=False, help='student_name参数类型不正确或缺失')
        parser.add_argument('phone', location='form', required=False, help='phone参数类型不正确或缺失')
        parser.add_argument('lesson_id', location='form', required=False, help='lesson_id参数类型不正确或缺失')
        try:
            temp = flask.g.user
            data = parser.parse_args()
            data = commons.put_remove_none(**data)
            res = StudentService.update(student_id=temp.UserID, **data)
            if res.get("code") != RET.OK:
                logger.error(res.get("data").get("error"))
                return jsonify(ResponseParser.parse_res(**res))
            logger.info("chang sysuser's information success")
            return jsonify({
                "code": RET.OK,
                "message": "修改成功",
            })

        except BadRequest as e:
            logger.error(str(e))
            return jsonify(ResponseParser.parse_param_error(error=str(e)))

        except Exception as e:
            logger.warning(str(e))
            return jsonify(ResponseParser.parse_unknown_error(error=str(e)))


# 删除学生
class StuDelResource(Resource):
    @classmethod
    @TokenRequire
    def delete(cls):
        parser = reqparse.RequestParser()
        parser.add_argument('student_id', location='form', required=True, help='student_id参数类型不正确或缺失')
        try:
            temp = flask.g.user
            data = parser.parse_args()
            data = commons.put_remove_none(**data)
            res = StudentService.delete(administrator_id=temp.UserID[0][0][0], student_id=data['student_id'])
            res['data']['student_id'] = res['data']['student_id'][0]
            if res.get("code") != RET.OK:
                logger.error(res.get("data").get("error"))
                return jsonify({
                    "code": res.get("code"),
                    "error": res.get("data").get("error"),
                    "message": res.get("message"),
                })

            logger.info("delete risky note success")
            return jsonify(res)
        except BadRequest as e:
            logger.error(str(e))
            return jsonify(ResponseParser.parse_param_error(error=str(e)))
        except Exception as e:
            logger.warning(str(e))
            return jsonify(ResponseParser.parse_unknown_error(error=str(e)))


# 修改学生密码
class StudentUpdatePasswordResource(Resource):
    @classmethod
    def put(cls):
        parser = reqparse.RequestParser()
        parser.add_argument('student_id', location='form', required=False, help='student_id参数类型不正确或缺失')
        parser.add_argument('password', location='form', required=False, help='password参数类型不正确或缺失')
        parser.add_argument('phone', location='form', required=False, help='phone参数类型不正确或缺失')
        try:
            data = parser.parse_args()
            data = commons.put_remove_none(**data)
            res_phone = StudentService.get(student_id=data['student_id'])
            if RSAEncryptionDecryption.decrypt(cipher_text=res_phone['data'][0]['phone']) == data['phone']:
                res = StudentService.update(**data)
                if res.get("code") != RET.OK:
                    logger.error(res.get("data").get("error"))
                    return jsonify(ResponseParser.parse_res(**res))
                logger.info("chang sysuser's information success")
                return jsonify({
                    "code": RET.OK,
                    "message": "修改成功",
                })
            else:
                return jsonify({
                    "error": 'phone error',
                    "message": '修改失败'
                })

        except BadRequest as e:
            logger.error(str(e))
            return jsonify(ResponseParser.parse_param_error(error=str(e)))

        except Exception as e:
            logger.warning(str(e))
            return jsonify(ResponseParser.parse_unknown_error(error=str(e)))


# 修改学生头像
class StudentImgUpdateResource(Resource):
    @classmethod
    @TokenRequire
    def post(cls):
        parser = reqparse.RequestParser()
        parser.add_argument('avatar', location='form', required=False, help='avatar参数类型不正确或缺失')
        try:
            temp = flask.g.user
            data = parser.parse_args()
            data = commons.put_remove_none(**data)
            data['avatar'] = data['avatar'].encode()
            res = StudentService.update(student_id=temp.UserID, **data)
            if res.get("code") != RET.OK:
                logger.error(res.get("data").get("error"))
                return jsonify(ResponseParser.parse_res(**res))
            logger.info("chang sysuser's information success")
            return jsonify({
                "code": RET.OK,
                "message": "修改成功",
            })

        except BadRequest as e:
            logger.error(str(e))
            return jsonify(ResponseParser.parse_param_error(error=str(e)))

        except Exception as e:
            logger.warning(str(e))
            return jsonify(ResponseParser.parse_unknown_error(error=str(e)))